<div class="loader">
      <p><img src="images/loader.gif" alt="Loading..." /></p>
</div>

<!-- Manage Bills //-->

<%@ page import="com.checkfree.isolutions.customer.persist.*" %>
<%@ page import="com.checkfree.isolutions.statement.*" %>
<%@ page import="com.checkfree.isolutions.statement.persist.*" %>
<%@ page import="com.myebills.ebpsfrontend.cust.utils.*" %>
<%@ page import="com.myebills.ebpsfrontend.cust.controller.*" %>
<%@ page import="com.checkfree.isolutions.property.Properties" %>
<%@ page import="com.checkfree.isolutions.property.PropertiesConfig" %>
<%@ page import="java.util.*" %>
<%@ page import="java.net.*" %>
<%@ page import="java.text.*" %>
<%@ page import="org.joda.time.*" %>
<%@ include file="../@functions.jsp" %>
<%
    final EbppxEcsUser ecsUser = (EbppxEcsUser) session.getAttribute(EbppxConstants.ECS_USER);
	final String randomKey = (String) session.getAttribute(EbppxConstants.RANDOM_KEY);
	final String statementId = (String) session.getAttribute("statementId");
	final String statementsCount = (String) session.getAttribute("statementsCount");
	int stmtsCount = 0;
	String amt = "";
	String ref = "";
	String msisdn = "";
	String userid = "";
	String stmtDate = "";
	String accno = "";
	String phoneNo = "";
	String simNo = "";
	String tempPhoneNo = "";
	String tempSimNo = "";
	String keySuffix = "_GSM_Key";
	String accessType = "";
	String compareURL = "CompareBill_v1r00"+statementId+"&comp=1";
	String DOWNLOAD_URL = "DownloadBill_v1r00"+statementId;
	String telDetUrl = "ChargesDetails_v1r00"+statementId;
	String telSummUrl = "CusTelSumm"+statementId;
	boolean onNotice = false;
	String currSdate = "";
	
	List simList = new ArrayList();
	int count = 0;
	
	if(statementsCount != null){
		stmtsCount = Integer.parseInt(statementsCount);
	}
	
	if(ecsUser != null){
		userid = ecsUser.getUserId();
		msisdn = ecsUser.getMsisdn();
		accno = ecsUser.getSAccount();
		simNo = ecsUser.getSimNo();
		accessType = ecsUser.getAccessType();
		if(msisdn != null){
			phoneNo = msisdn;
		}
	}
	
	com.checkfree.isolutions.statement.persist.Statement cfiStatement = (com.checkfree.isolutions.statement.persist.Statement)request.getAttribute(EbppxConstants.CFI_STATEMENTS);
	if(cfiStatement!=null){
	    boolean found = false;
		int phoneIndex = 0;
		StatementSection cfiRootSection = cfiStatement.getRootSection();
		ref = EbppxUtil.htmlEncode(cfiRootSection.getFieldText("ReferenceNumber"));
		amt = EbppxUtil.htmlEncode((cfiRootSection.getFieldText("TotalAmountDue")).replaceAll(" ",""));
		session.setAttribute("totalAmountDue", amt);
		final Date dtVal = cfiStatement.getDate();
		final DateFormat dfdisp = new SimpleDateFormat("dd MMM yyyy");
		stmtDate = EbppxUtil.htmlEncode(dfdisp.format(dtVal));
		
		Date todayDt = new Date();
		final DateFormat dfcompare = new SimpleDateFormat("yyyyMM");
		final DateFormat currDateFormat = new SimpleDateFormat("dd/MM/yyyy");
		String dt1 = dfcompare.format(todayDt);
		String dt2 = dfcompare.format(dtVal);
		Date addedDt = addMonths(dtVal,1);
		int daysBetween = Days.daysBetween(new DateTime(addedDt), new DateTime(todayDt)).getDays();
		currSdate = currDateFormat.format(addedDt);
		
		if(!dt1.equals(dt2) && ( daysBetween >= 0 && daysBetween <= 2)){
			onNotice = true;
		} 
		
		StatementSection phoneNumberSection = null;
		StatementSection cfiSection = cfiRootSection.getSection("DetailsOfChargesSection");
        if (cfiSection != null){
            int sectionCount = (int) cfiSection.getSectionCount("PhoneNumberSection");
			int simIncrement = 0;
			
            for ( int index = 0; index < sectionCount; index++) {
                StatementSection cfiRSection0 = cfiSection.getRepeatSection("PhoneNumberSection", index);
                String str = cfiRSection0.getFieldText("PhoneNumber");


                if(str.indexOf(":")>=0){
					StringTokenizer st = new StringTokenizer(str,":");
					str = EbppxUtil.nullToEmpty(st.nextToken());
					str = str.replaceAll("\\(","");
					str = str.replaceAll("\\)","");
					if(!str.substring(0,2).equals("60")){
						str = "6"+str;
					}
				}

                if (phoneNo.equals(str)){
					simIncrement++;
                    found = true;
					String tempSimNo_1 = cfiRSection0.getFieldText("SimNumber");

					if(tempSimNo_1 != null && tempSimNo_1.indexOf(":")>=0){
						StringTokenizer stTempSim = new StringTokenizer(tempSimNo_1,":");
						tempSimNo_1 = EbppxUtil.nullToEmpty(stTempSim.nextToken());
						tempSimNo_1 = tempSimNo_1.replaceAll("\\(", "");
						tempSimNo_1 = tempSimNo_1.replaceAll("\\)","");
						simList.add(tempSimNo_1);

						if(simNo.equals("") && simIncrement == 1){
							phoneNumberSection = cfiRSection0;
							tempSimNo = tempSimNo_1;
							phoneIndex = index;
						}
						else if(simNo.equals(tempSimNo_1)){
							phoneNumberSection = cfiRSection0;
							tempSimNo = tempSimNo_1;
							phoneIndex = index;
						}
					}else{
						cfiSection = cfiRSection0;
						phoneNumberSection = cfiRSection0;
						phoneIndex = index;
						break;
					}
                }
            }
            if (!found){
                cfiSection = null;
            }
        }
/*
Section 0:			ItemsWithoutRebateSection
Section 0_0:		PaymentsSection
Section 0_1:		AdjustmentsSection
Section 0_2:		AdjustmentsServiceTaxSection


Section 1:			ItemsWithRebateSection
Section 1_0:		RegistrationChargesSection
Section 1_1:		AccessChargesSection
Section 1_2:		ValueAddedServicesSection
Section 1_3:		UsageChargesSection
Section 1_4:		DiscountAndRebatesSection
Section 1_5:		OtherChargesAndCreditSection
Section 1_6:		ServiceTaxSection
Section 1_7:		MonthlyChargesSection
Section 1_8:		AdvantageSavingsSection
Section 1_total:	TotalLineChargesSection
*/
	if(found){	
		StatementSection cfiItemsWithoutRebateSection = null;
		StatementSection cfiSection2 = null;
		StatementSection cfiDiscountRebatesSection = null;
		StatementSection cfiServiceTaxSection = null;
		StatementSection cfiTotalLineChargesSection = null;
		StatementSection cfiMonthlyChargesSection = null;
		StatementSection cfiValueAddedServicesSection = null;
		StatementSection cfiUsageChargesSection = null;
		StatementSection cfiDomesticCallsSection = null;
		StatementSection cfiAdvantageSavingsSection = null;
		StatementSection cfiOtherChargesAndCreditSection = null;
		StatementSection cfiRegistrationChargesSection = null;
		StatementSection cfiAccessChargesSection = null;
		if(cfiSection != null) {
			cfiItemsWithoutRebateSection = phoneNumberSection.getSection("ItemWithRebateSection");
			cfiSection2 = phoneNumberSection.getSection("RoamingCallsSection");
			if(cfiItemsWithoutRebateSection != null) {
				
				cfiRegistrationChargesSection 	= cfiItemsWithoutRebateSection.getSection("RegistrationChargesSection");
	            cfiAccessChargesSection 		= cfiItemsWithoutRebateSection.getSection("AccessChargesSection");
				cfiValueAddedServicesSection	= cfiItemsWithoutRebateSection.getSection("ValueAddedServicesSection");
				cfiUsageChargesSection 			= cfiItemsWithoutRebateSection.getSection("UsageChargesSection");
				cfiDiscountRebatesSection 		= cfiItemsWithoutRebateSection.getSection("DiscountAndRebatesSection");
				cfiOtherChargesAndCreditSection	= cfiItemsWithoutRebateSection.getSection("OtherChargesAndCreditSection");
				cfiServiceTaxSection 			= cfiItemsWithoutRebateSection.getSection("ServiceTaxSection");
				cfiMonthlyChargesSection 		= cfiItemsWithoutRebateSection.getSection("MonthlyChargesSection");
				cfiAdvantageSavingsSection 		= cfiItemsWithoutRebateSection.getSection("AdvantageSavingsSection");
				cfiTotalLineChargesSection 		= cfiItemsWithoutRebateSection.getSection("TotalLineChargesSection");		
			}
		}
			String totalLineChargesSection = "0";
			if(cfiTotalLineChargesSection != null){
				totalLineChargesSection = cfiTotalLineChargesSection.getFieldText("Total");
			}
			double totalMonthlyCharges = 0;
			if(cfiMonthlyChargesSection != null){
				totalMonthlyCharges = getSectionTotal(cfiMonthlyChargesSection);
			}
			double totalRegistrationCharges = 0;
			if(cfiRegistrationChargesSection != null){
				totalRegistrationCharges = getSectionTotal(cfiRegistrationChargesSection);
			}
			double totalAccessChargesSection = 0;
			if(cfiAccessChargesSection != null){
				totalAccessChargesSection = getSectionTotal(cfiAccessChargesSection);
			}
			double totalVAS = 0;
			if(cfiValueAddedServicesSection != null){
				totalVAS = getSectionTotal(cfiValueAddedServicesSection);
			}
 			double totalUsageCharges = 0;
 			List usage = new ArrayList();
			if(cfiUsageChargesSection != null){
				int sectionCount1_3 = (int) cfiUsageChargesSection.getSectionCount("RepeatSection");
                for (int index1_3 = 0; index1_3 < sectionCount1_3; index1_3++) {
                    StatementSection cfiRSection1_3 = cfiUsageChargesSection.getRepeatSection("RepeatSection", index1_3);
					double total =0;
                    String item = cfiRSection1_3.getFieldText("Item");
					if(item.equals("Usage Charges")){
						totalUsageCharges = getSectionTotal(cfiUsageChargesSection);
						usage.add(item+"_"+totalUsageCharges);
					}else{
						int subRepeatSectionCount = (int) cfiRSection1_3.getSectionCount("SubRepeatSection");
						if(subRepeatSectionCount == 0){
							double amount = getFieldAmount(cfiRSection1_3,"Amount");
							total += amount;
						}else{
							for (int index1_1 = 0; index1_1 < subRepeatSectionCount; index1_1++) {
								StatementSection subRepeatSection = cfiRSection1_3.getRepeatSection("SubRepeatSection", index1_1);
								if(subRepeatSection != null){
									String repeatItem1 = subRepeatSection.getFieldText("Item");
									String amount1 = subRepeatSection.getFieldText("Amount");
									double amount = getFieldAmount(subRepeatSection,"Amount");
									total += amount;
								}
							}
						}
						totalUsageCharges += total;
						usage.add(item+"_"+total);
					}
				}
			}
			double totalAdvantageSavings = 0;
			if(cfiAdvantageSavingsSection != null){
				totalAdvantageSavings = getSectionTotal(cfiAdvantageSavingsSection);
			}
			double totalDiscountRebates = 0;
			if(cfiDiscountRebatesSection != null){
				totalDiscountRebates = getSectionTotal(cfiDiscountRebatesSection);
			}
			double totalServiceTax = 0;
			if(cfiServiceTaxSection != null){
				totalServiceTax = getSectionTotal(cfiServiceTaxSection);
			}
			double totalOtherChargesAndCredit = 0;
			if(cfiOtherChargesAndCreditSection != null){
				totalOtherChargesAndCredit = getSectionTotal(cfiOtherChargesAndCreditSection);
			}
				
//compare url with simno
compareURL = "CompareBill_v1r00"+statementId+"&comp=1&simno="+tempSimNo;
%>
<!-- Start draw html//-->
<!-- Current Month (Principle Number) //-->

<div class="manage-bills col1">
	<div class="manage-bill month0">
		<div class="detailed-bill">
			<div class="charges">
				<ul>
					<li class="details">
						<h4>Bill date: <%=stmtDate%></h4>
						<%if(onNotice)out.print("<p>Note: Your bill will be made available within 3 working days from the bill date of "+currSdate+".</p>");%>
						<h1></h1>
<%						if(simList.size() > 0){ %>
						<form>
						<div class="multisim">
						<h5>SIM Card Number :</h5> 
							<span class="select-custom">
								<select name="multisim" onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
									<% if(simList.size() > 0) {
										for(int i = 0; i < simList.size(); i++){
											String host = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
											String urlToDirect = host+"/cust_sso/CusBillList_v1r00?simno="+simList.get(i);
									%>
										<option value="<%=urlToDirect%>" <%if(tempSimNo.equals(simList.get(i))){%>selected<%}%>><%=simList.get(i)%></option>
									<%}%>
									<%}%>
								</select>
							</span>
						</div>
						</form>
<%}%>					
						<br />
					
					<h6>Total Line Charges <span class="total-line-charges"><sup>RM</sup><%=totalLineChargesSection%></span></h6>
					</li>
					<!-- Display monthly charges//-->
					<%if(totalMonthlyCharges > 0){
						String param = EncryptionHelper.encodeURL(EncryptionHelper.encrypt("Monthly Charges", randomKey));
						String param1 = EncryptionHelper.encodeURL(EncryptionHelper.encrypt("MonthlyChargesSection", randomKey));
					%>
					<li class="green monthly-charges <%count++;if((count %2) == 0){%> alt <%}%>"><label>Monthly Charges</label><sup>RM</sup><%=formatAmount(totalMonthlyCharges)%><br />
						<p><a href="<%=telDetUrl%>&phoneIndex=<%=phoneIndex%>&type=<%=param%>&typeIndex=<%=param1%>" class="detailed-charges">Details of charges</a></p></li>
					<%}%>
					<!-- Display totalRegistrationCharges //-->
					<%if(totalRegistrationCharges > 0){
						String param = EncryptionHelper.encodeURL(EncryptionHelper.encrypt("Registration Charges", randomKey));
						String param1 = EncryptionHelper.encodeURL(EncryptionHelper.encrypt("RegistrationChargesSection", randomKey));%>
					<li class="green monthly-charges <%count++;if((count %2) == 0){%> alt <%}%>"><label>Registration Charges</label><sup>RM</sup><%=formatAmount(totalRegistrationCharges)%><br />
						<p><a href="<%=telDetUrl%>&phoneIndex=<%=phoneIndex%>&type=<%=param%>&typeIndex=<%=param1%>" class="detailed-charges">Details of charges</a></p></li>
					<%}%>
					<!-- Display totalAccessChargesSection //-->
					<%if(totalAccessChargesSection > 0){
						String param = EncryptionHelper.encodeURL(EncryptionHelper.encrypt("Access Charges", randomKey));
						String param1 = EncryptionHelper.encodeURL(EncryptionHelper.encrypt("AccessChargesSection", randomKey));%>
					<li class="green monthly-charges <%count++;if((count %2) == 0){%> alt <%}%>"><label>Access Charges</label><sup>RM</sup><%=formatAmount(totalAccessChargesSection)%><br />
						<p><a href="<%=telDetUrl%>&phoneIndex=<%=phoneIndex%>&type=<%=param%>&typeIndex=<%=param1%>" class="detailed-charges">Details of charges</a></p></li>
					<%}%>
					<!-- Display VAS-->
					<%if(totalVAS > 0){
						String param = EncryptionHelper.encodeURL(EncryptionHelper.encrypt("Value Added Services", randomKey));
						String param1 = EncryptionHelper.encodeURL(EncryptionHelper.encrypt("ValueAddedServicesSection", randomKey));%>
					<li class="lightgreen <%count++;if((count %2) == 0){%> alt <%}%>"><label>Value Added Services</label><sup>RM</sup><%=formatAmount(totalVAS)%><br />
						<p><a href="<%=telDetUrl%>&phoneIndex=<%=phoneIndex%>&type=<%=param%>&typeIndex=<%=param1%>" class="detailed-charges">Details of charges</a></p></li>
					<%}%>
					<%if(totalUsageCharges > 0){
						int usageIndex = 0;
						while(usageIndex < usage.size()){
						String[] item = usage.get(usageIndex).toString().split("_");
						String param = EncryptionHelper.encodeURL(EncryptionHelper.encrypt(item[0], randomKey));
						String param1 = EncryptionHelper.encodeURL(EncryptionHelper.encrypt(item[0].replaceAll(" ", "")+"Section", randomKey));
						%>
								<li class="seagreen domestic-charges <% count++;if((count %2) == 0){%> alt <%}%>"><label><%=item[0]%></label><sup>RM</sup><%=formatAmount(Double.parseDouble(item[1]))%><br />
								<%if(!(item[0].equals("Usage Charges"))){%>
									<p><a href="<%=telDetUrl%>&phoneIndex=<%=phoneIndex%>&type=<%=param%>&typeIndex=<%=param1%>" class="detailed-charges">Details of charges</a></p></li>
						<%		}
						usageIndex++;
						}
					}
					if(totalAdvantageSavings > 0){
						String param = EncryptionHelper.encodeURL(EncryptionHelper.encrypt("Advantage Savings", randomKey));
						String param1 = EncryptionHelper.encodeURL(EncryptionHelper.encrypt("AdvantageSavingsSection", randomKey));%>
					<li class="babyblue roaming-charges <% count++;if((count %2) == 0){%> alt <%}%>"><label>Advantage Savings</label><sup>RM</sup><%=formatAmount(totalAdvantageSavings)%><br />
						<p><a href="<%=telDetUrl%>&phoneIndex=<%=phoneIndex%>&type=<%=param%>&typeIndex=<%=param1%> class="detailed-charges">Details of charges</a></p></li>
					<%}%>
					<%if(totalDiscountRebates != 0){
						String param = EncryptionHelper.encodeURL(EncryptionHelper.encrypt("Discounts & Rebates", randomKey));
						String param1 = EncryptionHelper.encodeURL(EncryptionHelper.encrypt("DiscountAndRebatesSection", randomKey));%>
					<li class="dullerblue discounts-rebates <% count++;if((count %2) == 0){%> alt <%}%>"><label>Discounts &amp; Rebates</label><sup>RM</sup><%=formatAmount(totalDiscountRebates)%><br />
						<p><a href="<%=telDetUrl%>&phoneIndex=<%=phoneIndex%>&type=<%=param%>&typeIndex=<%=param1%>" class="detailed-charges">Details of charges</a></p></li>
					<%}%>
					<%if(totalOtherChargesAndCredit != 0){
						String param = EncryptionHelper.encodeURL(EncryptionHelper.encrypt("Other Charges & Credit", randomKey));
						String param1 = EncryptionHelper.encodeURL(EncryptionHelper.encrypt("OtherChargesAndCreditSection", randomKey));%>
					<li class="dullerblue discounts-rebates <% count++;if((count %2) == 0){%> alt <%}%>"><label>Other Charges &amp; Credit</label><sup>RM</sup><%=formatAmount(totalOtherChargesAndCredit)%><br />
						<p><a href="<%=telDetUrl%>&phoneIndex=<%=phoneIndex%>&type=<%=param%>&typeIndex=<%=param1%>" class="detailed-charges">Details of charges</a></p></li>
					<%}%>
					<%if(totalServiceTax != 0){%>
					<li class="blue service-tax <% count++;if((count %2) == 0){%> alt <%}%>"><label>Service Tax</label><sup>RM</sup><%=formatAmount(totalServiceTax)%><br />
						<p>Monthly Charges and Value Added Services</p>
					<%}%>
					<!-- Draw empty column if odd//-->
					<%if((count %2) != 0){%>
					<li class="blue service-tax alt"><br />
						<br />
					<%}%>
					</li>
				</ul>
			</div>
		</div>
	</div>
	<div class="manage-bill-actions">
		<form id="cusPayment" name="cusPayment" method="post" action="CusConfirmPayment.jsp">
			<input id="accid" name="accid" type="hidden" value="<%=accno%>">
			<input id="statid" name="statid" type="hidden" value="<%=ref%>">
			<input id="amt" name="amt" type="hidden" value="<%=amt%>">
			<input id="lflag" name="lflag" type="hidden" value="E">
		</form>
		<a href="#" class="btn paynow">Pay Bill Now<i class="icon-chevron-right"></i></a>
<%				if(stmtsCount > 1){
%>					<a href=<%=compareURL%> class="btn blue">View Past Bill</a>
<%				}else{%>
					<a href="popups/compare-alert.jsp" class="btn blue pop">View Past Bills</a>
				<%}
%>
<%	if(accessType.equals("P")){
%>		<a href=<%=DOWNLOAD_URL%> class="download-bill" target="_blank">Download Bill</a>
<%	}
%>
	</div>
</div>
<!-- #END Current Month (Principle Number) //-->
		
<%	}else{//if not found %>
		<div class="manage-bills col1">
			<p>There are no bills due right now.</p>
			<!-- <p>The next payment amount due is on <strong>24th February 2013</strong>.</p> -->
		</div>
	<%}
}else{//cfi statement not found %>
	<div class="manage-bills col1">
			<p>There are no bills for this account.</p>
			<!-- <p>The next payment amount due is on <strong>24th February 2013</strong>.</p> -->
	</div>
<% }%>

<script type="text/javascript">
	$(document).ready(function() {
		function hideSpinner() {
			document.getElementById('manage-bills-loader').style.display = "none";
		}
	});
</script>

<script type="text/javascript">
	$(document).ready(function() {

	    $(".detailed-charges,._paynow,.pop,.compare").fancybox({
	    	type		: 'ajax',
			width		: 600,
			height		: 600,
			fitToView	: true,
			autoSize	: true,
			closeClick	: false,
			openEffect	: 'fade',
			closeEffect	: 'fade',
			padding		: 0
		});

	    $(".paynow").click(function(event){
	    	event.preventDefault();
	    	 $("#cusPayment").submit();
	    });
	    
	    $("#cusPayment").submit(function() {
	        $.fancybox.showLoading(); // start fancybox loading animation
	        $.ajax({
	            data: $(this).serialize(), // get the form data
	            type: $(this).attr('method'), // GET or POST
	            url: $(this).attr('action'), // the file to call
	            success: function(response) { // on success..
	                $.fancybox({ 'content' : response }); // target response to fancybox
	            },
	            complete: function() { // on complete...
	                $.fancybox.hideLoading(); //stop fancybox loading animation
	            }
	        });
	        return false; // stop default submit event propagation
	    });
	    
		$(".download-bill").fancybox({
	    	type		: 'ajax',
			width		: 600,
			height		: 600,
			fitToView	: true,
			autoSize	: true,
			closeClick	: false,
			openEffect	: 'fade',
			closeEffect	: 'fade',
			padding		: 0
		});

		$('.col1 .compare1').click(function() {
			$('.col1').slideUp();
			$('.col2').slideDown("fast", function() {
				$("html, body").animate({ scrollTop: 0 }, "fast");
			});
			var width = $(window).width();
			if (width <= 492) {
				var containerWidth = $('.manage-bills-container .manage-bill').width();
				$('.manage-bills-container').find('.manage-bills').animate({
					marginLeft: '-='+containerWidth+'px'
				}, 500);
			}
		});

		$('.manage-bills-container .month0 .compare1').click(function() {
			var containerWidth = $(this).parents(".manage-bill").width();
			$(this).parents('.manage-bills-container').find('.manage-bills').animate({
				marginLeft: '-='+containerWidth+'px'
			}, 500);
		});

		$('.manage-bills-container .month1 .close-mobile').click(function() {
			$(this).parents('.manage-bills-container').find('.manage-bills').animate({
				marginLeft: '0px'
			}, 500);
		});
		
		$(".loader").fadeOut(2000, function() {
			$(".manage-bills").fadeIn(1000,function() {
				iframeResizePipe();
			});  						
		});
		
	});
</script>
